package cn.wolfcode.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Component
public class AliOSSUtils {

////    @Value("${aliyun.oss.endpoint}")
//    private   String endpoint;
//    //阿里云  两个密钥
////    @Value("${aliyun.oss.accessKeyid}")
//    private  String accessKeyid;
////    @Value("${aliyun.oss.accessKeySecret}")
//    private  String accessKeySecret;
////    @Value("${aliyun.oss.bucketName}")
//    private  String bucketName;
    @Autowired
    private AliOSSProperties aliOSSProperties;

    public String upload(MultipartFile multipartFile) throws IOException {
        //获取上传问文件  输入流
        InputStream inputStream = multipartFile.getInputStream();

        //避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //上传文件 到 OSS
        OSS ossClient=new OSSClientBuilder().build(aliOSSProperties.getEndpoint(),aliOSSProperties.getAccessKeyid(),aliOSSProperties.getAccessKeySecret());
        ossClient.putObject(aliOSSProperties.getBucketName(),fileName,inputStream);
        /**
         * https://javafk-oss.oss-cn-beijing.aliyuncs.com/image/55.jpg
         */
        StringBuffer stringBuffer = new StringBuffer(aliOSSProperties.getEndpoint());
        stringBuffer.insert(8,aliOSSProperties.getBucketName()+".").append("/").append(fileName);
        System.out.println(stringBuffer);
        return stringBuffer.toString();
    }

}
